package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.vo.TravelStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;
    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo") TravelQuery qo) {
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "travel/list";
    }

    @RequestMapping("/detail")
    public String detail(Model model, Long id) {

        //detail
        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        detail.setTravelContent(content);
        model.addAttribute("detail", detail);

        //toasts
        Destination destination = detail.getDest();
        List<Destination> toasts = destinationService.getToasts(destination.getId());
        toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts", toasts);

        //sds
        List<StrategyDetail> sds = strategyDetailService.getViewTop3(destination.getId());
        model.addAttribute("sds", sds);

        //ts
        List<Travel> ts = travelService.getViewNumTop3(destination.getId());
        model.addAttribute("ts", ts);

        //list
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setCurrentPage(1);
        qo.setPageSize(100000);
        List list = travelCommentService.query(qo).getContent();
        model.addAttribute("list", list);
        return "travel/detail";
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {

        if (id != null) {
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv", travel);
        }

        //dests
        List<Destination> dests = destinationService.getDestsByDeep(3);
        model.addAttribute("dests", dests);

        return "travel/input";
    }

    @Value("${file.path}")
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Travel travel, HttpServletRequest request, HttpServletResponse response) {
        //获取当前登录用户
        //从cookie中获取token之后获得Redis中的用户
        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getUserByToken(token);
        travel.setAuthor(user);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    @RequestMapping("/info")
    @ResponseBody
    public Object info(@UserParam UserInfo userInfo) {
        return userInfo;
    }

    @RequestMapping("/save")
    @ResponseBody
    public Object save(UserInfo userInfo) {
        return userInfo;
    }

    @RequestMapping("/commentAdd")
    public String commentAdd(Model model, TravelComment comment, @UserParam UserInfo user) {
        System.out.println(user);
        //c
        comment.setUserId(user.getId());
        comment.setHeadUrl(user.getHeadImgUrl());
        comment.setCity(user.getCity());
        comment.setLevel(user.getLevel());
        comment.setUsername(user.getNickname());
        TravelComment travelComment = travelCommentService.save(comment);
        model.addAttribute("c", travelComment);
        //floor
        model.addAttribute("floor", travelCommentService.getCount(comment.getTravelId()));
        return "travel/commentTpl";
    }
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long tId, @UserParam UserInfo user) {
        //登录验证
        AjaxResult result = new AjaxResult();
        if (user == null){
            result.setSuccess(false);
            result.setMsg("请先登录");
            result.setCode(102);
            return result;
        }
        if (travelStatisRedisService.favor(tId,user.getId())){
            //收藏
            result.setSuccess(true);
        }else {
            //取消收藏
            result.setSuccess(false);
        }
        return result;
    }
    @RequestMapping("/share")
    @ResponseBody
    public String zone(HttpServletResponse response, String title, String content, String pic, String url,String key,@UserParam UserInfo userInfo) throws IOException {
        //拼接网址
        String urlStr=null;
        if(userInfo!=null){
            if("qz".equals(key)){
                urlStr = "http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey"
                        + "?url="+url
                        +"&title="+title
                        +"&summary="+content
                        +"&pics="+pic;
            }else {
                urlStr = "http://v.t.sina.com.cn/share/share.php"
                        + "?url="+url
                        +"&title="+title
                        +"&summary="+content
                        +"&pic="+pic;
            }
        }
        return urlStr;

    }
}
